<template>
  <div>
    <a-modal :width="880" title="退费" :visible="show" @cancel="cancel">
      <template slot="footer">
        <a-button @click="cancel"> 取消 </a-button>
        <a-button key="submit" type="primary" @click="ok"> 下一步 </a-button>
      </template>
      <!-- tabs切换 -->
      <a-spin :spinning="spinning">
        <div class="employee-selector-wrapper2">
          <div>
            <div class="employee-selector-block">
              <a-input-search
                placeholder="输入姓名或手机号搜索员工"
                style="width: 100%"
                allowClear
                v-model="querys"
                @search="searchPeople"
                @change="changePeople"
              />
            </div>
            <a-tabs
              default-active-key="3"
              :activeKey="mode"
              @change="onChangeTab"
              style="margin-bottom: 10px; width: 500px"
              size="small"
              :tabBarGutter="15"
            >
              <a-tab-pane v-for="item in $store.state.enums.postTypeLst" :key="item.value + ''" :tab="item.title">
                <div class="employee-selector">
                  <div v-for="(item, index) in treeData" :key="index" class="mg_t10">
                    <div class="tree-item" @click="chose(item, treeData)">
                      <span>
                        <img src="@/assets/icons/person1.png" style="width: 30px; height: 30px; margin-right: 10px" />
                        {{ item.name }}
                        {{ item.phone ? "(" + item.phone + ")" : "" }}
                      </span>
                      <i
                        v-if="item.isSelected"
                        v-on:click.stop="chose(item, treeData)"
                        style="font-size: 19px"
                        class="iconfont icon-check-circle-fill primary_color"
                      >
                      </i>
                      <img
                        v-else
                        v-on:click.stop="chose(item, treeData)"
                        src="@/assets/icons/未选择.png"
                        style="width: 18px; height: 18px"
                      />
                    </div>
                  </div>
                </div>
                <a-pagination
                  v-model="current"
                  :page-size-options="pageSizeOptions"
                  :total="total"
                  show-size-changer
                  show-less-items
                  :page-size="pageSize"
                  @showSizeChange="onShowSizeChange"
                  @change="onPageChange"
                >
                  <template slot="buildOptionText" slot-scope="props">
                    <span>{{ props.value }}条/页</span>
                  </template>
                </a-pagination>
              </a-tab-pane>
            </a-tabs>
          </div>
          <div class="verticalBar" />
          <div class="employee-selector-block2">
            <div class="employee-selector-title">已经选择人员 {{ selectedListTemp.length }}人</div>
            <div class="employee-selector">
              <div v-for="(item, i) in selectedListTemp" :key="i" class="employee-selector-item">
                <div>
                  <img src="@/assets/icons/person1.png" style="width: 30px; height: 30px; margin-right: 10px" />
                  {{ item.name }}
                </div>
                <img @click="deleteItem(item)" src="@/assets/icons/删除.png" style="width: 20px; height: 20px" />
              </div>
            </div>
          </div>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
const columns = [
  { title: "姓名", dataIndex: "name", key: "name", width: 80 },
  { title: "手机号", dataIndex: "phone", key: "phone", width: 120 },
  { title: "身份证号", dataIndex: "idCard", key: "idCard", width: 180 }
];

import { listByCompanyIdGet } from "@/api/company/contract";
import moment from "moment";
import { tuifeiList, deleteEmpListByIdCards } from "./api";
export default {
  props: {
    show: {
      type: Boolean,
      default: false
    },
    number: {
      type: Number,
      default: 0
    },
    templateId: {
      type: Number,
      default: 0
    },
    defaultSelectedKeys: {
      type: Array,
      default: () => []
    },
    isOnlineOrLeave: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      form: {},
      columns,
      textContent: "",
      labelCol: { span: 7 },
      dataList: [],
      wrapperCol: { span: 16 },
      labelList: [],
      nameOrPhone: "",
      seniorVisible: false,
      chosenList: [],
      spinning: false,
      mode: "3",
      errorState: false,
      selectedRowKeys: [],
      isAllSelected: false,
      copyVisible: false,
      treeData: [],
      seniorList: [],
      checkStatue: 0,
      pagination: {
        pageSize: 10,
        total: 0,
        size: "small",
        current: 1,
        showTotal: (total) => `共 ${total} 条`
      },
      selectedListTemp: [],
      selectedKeysBeforeSearch: [],
      querys: "",
      postTypeValue: 3,

      pageSizeOptions: ["10", "20", "50", "100"],
      pageSize: 50,
      current: 1,
      total: 50
    };
  },
  watch: {
    textContent(e) {
      if (e) {
        this.errorState = false;
      }
    },

    show(val) {
      if (val) {
        this.selectedListTemp = [];
        this.selectedRowKeys = [];
        this.treeData = [];
        this.spinning = false;
        this.current = 1;
        this.postTypeValue = 3;
        this.mode = "3";

        if (this.defaultSelectedKeys.length !== this.selectedListTemp.length || this.defaultSelectedKeys.length === 0) {
          this.getSelectDepTree();
        }
      }
    }
  },
  mounted() {
    // this.getSelectDepTree();
  },
  methods: {
    reset() {
      this.textContent = "";
      this.errorState = false;
    },
    getEmpListByIdCards() {
      if (this.textContent !== "") {
        var arr = [];
        arr = this.textContent.split(/[\W]/);

        if (arr.length > 1) {
          // 减员仅允许单选
          this.$message.success("减员不支持多选");
          return;
        }
        deleteEmpListByIdCards(this.$store.state.hr.companyId, arr).then((res) => {
          if (this.selectedListTemp.length > 0) {
            this.chosenList = res.data.empInfoVOList.concat(this.selectedListTemp);
            this.chosenList = this.unique(this.chosenList);
          } else {
            this.chosenList = res.data.empInfoVOList;
          }
          this.textContent = res.data.idCardList.join(",");
          if (res.data.idCardList.length > 0) {
            setTimeout(() => {
              this.errorState = true;
            });
          }
        });
      }
    },
    copyOk() {
      if (this.chosenList.length === 0) {
        this.$message.success("请添加选择人员");
        return;
      }
      this.$emit("update:selectedList", this.chosenList);
      this.$emit(
        "update:selectThree",
        this.chosenList
          .slice(0, 3)
          .map((item) => item.name)
          .join(",")
      );
      this.copyVisible = false;
      this.$emit("change", this.chosenList);
    },
    deleteCopyItem(e) {
      this.chosenList.forEach((item, index) => {
        if (item.id === e.id) {
          this.chosenList.splice(index, 1);
        }
      });
    },
    deleteSeniorItem(e) {
      this.seniorList.forEach((item, index) => {
        if (item.id === e.id) {
          this.seniorList.splice(index, 1);
          this.selectedRowKeys.forEach((item2, index2) => {
            if (item2 === e.id) {
              this.selectedRowKeys.splice(index2, 1);
            }
          });
        }
      });
    },

    onSelectChange(selectedRowKeys, e) {
      // 减员仅允许单选
      if (selectedRowKeys.length > 2) {
        return;
      }
      this.selectedRowKeys = [];
      const h = selectedRowKeys[selectedRowKeys.length - 1];
      this.selectedRowKeys.push(h);
      selectedRowKeys = [];
      selectedRowKeys.push(h);

      // this.selectedRowKeys = selectedRowKeys;
      this.dataList.forEach((item) => {
        selectedRowKeys.forEach((item2) => {
          if (item.id === item2) {
            this.seniorList.push(item);
            this.seniorList = this.unique(this.seniorList);
          }
        });
      });
      // this.seniorList.forEach((item, index) => {
      //   if (selectedRowKeys.indexOf(item.id) === -1) {
      //     this.seniorList.splice(index, 1);
      //   }
      // });
      this.seniorList.forEach((item, index) => {
        if (this.selectedRowKeys.indexOf(item.id) === -1) {
          item.isSelectedItem = 2;
        }
      });
      var arr = [];
      this.seniorList.forEach((item, index) => {
        if (!item.isSelectedItem) {
          arr.push(item);
        }
      });
      this.seniorList = JSON.parse(JSON.stringify(arr));
    },
    unique(arr) {
      const res = new Map();
      return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1));
    },
    clearForm() {
      this.form = {};
    },

    seniorCancel() {
      this.seniorVisible = false;
      this.selectedRowKeys = [];
    },
    // 分页变化
    onPageChange(pageNumber) {
      this.current = pageNumber;
      this.getSelectDepTree();
    },
    rangeChange(e) {
      this.form.joinDateStart = e[0];
      this.form.joinDateEnd = e[1];
    },
    postTypeClick(value) {
      this.querys = "";
      this.nameOrPhone = this.query;
      this.postTypeValue = value;
      this.isAllSelected = false;
      this.current = 1;
      this.getSelectDepTree();
    },
    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize;
      this.current = 1;
      this.getSelectDepTree();
    },
    deleteItem(item) {
      item.isSelected = false;
      this.spinning = true;
      var that = this;
      setTimeout(function () {
        that.ergodic(item);
        that.spinning = false;
      }, "10");
    },
    chose(item, data) {
      // 减员单选逻辑
      if (!item.isSelected) {
        let id = "";
        var index2 = this.treeData.findIndex((it) => it.isSelected === true); // 删除之前选择的，维持单选状态
        if (index2 !== -1) {
          this.treeData[index2].isSelected = false;
          id = this.treeData[index2].id;
        }

        index2 = this.selectedListTemp.findIndex((it) => it.id === id); // 删除之前选择的，维持单选状态
        if (index2 !== -1) {
          this.selectedListTemp.splice(index2, 1); // 删除
          this.isAllSelected = false;
        }
      }

      item.isSelected = !item.isSelected;

      this.onChange(item);
    },
    getListByCompanyId() {
      listByCompanyIdGet({ companyId: this.$store.state.hr.companyId })
        .then(({ data }) => {
          this.labelList = data;
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    choseAll(data) {
      this.isAllSelected = !this.isAllSelected;
      var that = this;
      this.spinning = true;
      setTimeout(function () {
        for (var j = 0, len = data.length; j < len; j++) {
          data[j].isSelected = that.isAllSelected;
          that.ergodicAll(data[j]);
        }
        that.spinning = false;
      }, "10");
    },
    getAllEmp(data) {
      let count = 0;
      for (var j = 0, len = data.length; j < len; j++) {
        if (data[j].childList) {
          count += data[j].childList.length;
        }
      }
      return count;
    },
    onChangeTab(e) {
      this.querys = "";
      this.nameOrPhone = this.query;
      this.isAllSelected = false;
      this.current = 1;
      this.mode = e;
      this.getSelectDepTree();
    },
    onChange(item) {
      this.spinning = true;
      var that = this;
      setTimeout(function () {
        that.ergodic(item);
        that.spinning = false;
      }, "10");
    },

    onExpand(item) {
      if (!item.isExpand) {
        //
        this.spinning = true;
      } else {
        this.spinning = false;
      }
    },

    ergodic(item) {
      if (!item.isSelected) {
        var index = this.selectedListTemp.findIndex((it) => it.id === item.id); // 存在再删除，防止删除错误
        if (index !== -1) {
          this.selectedListTemp.splice(index, 1); // 删除
          this.isAllSelected = false;
        }
      } else {
        if (this.selectedListTemp.findIndex((it) => it.id === item.id) === -1) {
          // 不存在再添加，防止重复添加
          this.selectedListTemp.push(item);

          var count = this.treeData.length;
          var allSelect = true;
          for (var i = 0; i < count; i++) {
            if (!this.treeData[i].isSelected) {
              allSelect = false;
              break;
            }
          }
          this.isAllSelected = allSelect;
        }
      }
    },
    ergodicAll(item) {
      if (!item.isSelected) {
        var index = this.selectedListTemp.findIndex((it) => it.id === item.id); // 存在再删除，防止删除错误
        if (index !== -1) {
          this.selectedListTemp.splice(index, 1); // 删除
        }
      } else {
        if (this.selectedListTemp.findIndex((it) => it.id === item.id) === -1) {
          // 不存在再添加，防止重复添加
          this.selectedListTemp.push(item);
        }
      }
    },

    ergodicList(data, parent) {
      const list = data.filter((item) => item.hasChild);
      if (list.length > 0) {
        for (let i = 0; i < list.length; i++) {
          this.ergodicList(list[i].childList, list[i]);
        }
        if (parent) {
          parent.isSelected = data.length === data.filter((item) => item.isSelected).length;
        }
      } else {
        if (parent) {
          parent.isSelected = data.length === data.filter((item) => item.isSelected).length;
        }
      }
    },
    // 获取部门树
    getSelectDepTree(query) {
      if (query) {
        this.current = 1;
      }
      const params = {
        companyId: this.$store.state.hr.companyId,
        pageNo: this.current,
        pageSize: this.pageSize,
        postType: this.mode + ""
      };
      if (this.nameOrPhone) {
        params["nameOrPhone"] = this.nameOrPhone;
      }

      this.spinning = true;

      // 减员
      tuifeiList(params)
        .then((res) => {
          if (res.data.entities === null) {
            this.$message.success("暂无数据");

            res.data.entityCount = [];
            this.treeData = [];
            this.total = 0;
          } else {
            this.treeData = this.formatCompanyData(res.data.entities);
            this.total = res.data.entityCount;
            var count = this.treeData.length;
            var allSelect = true;
            for (var i = 0; i < count; i++) {
              if (!this.treeData[i].isSelected) {
                allSelect = false;
                break;
              }
            }
            this.isAllSelected = allSelect;
          }

          this.$nextTick(() => {
            this.spinning = false;
          });
        })
        .catch((err) => {
          console.log("debug logdebug log debug log --> ", err);
        });
    },
    formatCompanyData(company) {
      const parent = [];
      for (var key = 0; key < company.length; key++) {
        var selected = false;
        if (this.selectedListTemp.findIndex((it) => it.id === company[key].id) !== -1) {
          selected = true;
        }

        var emp = {
          id: company[key].id,
          name: company[key].name,
          phone: company[key].phone,
          idCard: company[key].idCard,
          depName: company[key].depName,
          positionName: company[key].positionName,
          isSelected: selected
        };

        parent.push(emp);
      }
      return parent;
    },
    formatEmployeeData(employee) {
      var emp = {
        id: employee.id,
        name: employee.name,
        phone: employee.phone,
        idCard: employee.idCard,
        depName: employee.depName,
        positionName: employee.positionName,
        isDept: false,
        isSelected: false,
        isExpand: false,
        hasChild: false
      };
      return emp;
    },
    searchPeople(query) {
      this.querys = query;
      this.nameOrPhone = query;
      this.selectedKeysBeforeSearch = this.selectedListTemp.map((item) => item.id);
      this.getSelectDepTree(query);
    },
    changePeople(e) {
      this.querys = e.target.value;
      if (e.target.value === "") {
        this.getSelectDepTree();
        this.selectedKeysBeforeSearch = this.selectedListTemp.map((item) => item.id);
      }
    },

    ok() {
      if (this.selectedListTemp.length === 0) {
        this.$message.success("请选择人员");
        return;
      }
      this.$emit("update:selectedList", this.selectedListTemp);
      this.$emit(
        "update:selectThree",
        this.selectedListTemp
          .slice(0, 3)
          .map((item) => item.name)
          .join(",")
      );
      this.$emit("update:show", false);
      this.$emit("change", this.selectedListTemp);
    },
    cancel() {
      this.$emit("update:show", false);
    }
    // update() {
    //   this.rulusList = [];
    //   salaryCalculateRulesListall().then(res => {
    //     if (res.data.length > 0) {
    //       res.data.map(item => {
    //         if (item.ruleType === 1 || item.ruleType === 3) {
    //           this.rulusList.push(item);
    //         }
    //       });
    //     }
    //   });
    // }
  }
};
</script>
<style lang="scss" scoped>
.employee-selector {
  height: 400px;
  margin-top: 2px;
  padding-right: 10px;
  margin-bottom: 10px;
  overflow: auto;
}
.employee-selector2 {
  height: 370px;
  margin-top: 2px;
  padding-right: 5px;
  margin-bottom: 10px;
  overflow: auto;
}
.postTypeL {
  display: flex;

  flex-direction: row;
  align-items: center;
}
.emyStatusRow {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.verticalBar {
  width: 1px;

  background: #e8e8e8;
  display: inline-block;
  margin-top: 40px;
  vertical-align: top;
  margin-right: 30px;
  margin-left: 30px;
  html,
  body,
  #app {
    height: 100%;
  }
}

.tree-item {
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  align-items: center;
  cursor: pointer;
  margin-top: 10px;
}
.tree-item2 {
  display: flex;
  flex-direction: row;
  align-items: center;
  cursor: pointer;
  margin-top: 10px;
  margin-bottom: 10px;
}
.employee-selector-wrapper2 {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  .employee-selector-block {
    width: 400px;
    margin-bottom: 20px;
    .employee-selector-title {
      width: 100%;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
    }
    .employee-selector {
      height: 400px;
      margin-top: 20px;
      padding-right: 20px;
      overflow: auto;
      .employee-selector-item {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
      }
    }
  }
  .employee-selector-block2 {
    width: 400px;
    .employee-selector-title {
      width: 100%;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
    }
    .employee-selector {
      height: 500px;
      margin-top: 20px;
      padding-right: 10px;
      overflow: auto;
      .employee-selector-item {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
      }
    }
  }
}
</style>
